#include "appdatamodel.h"

#include <QDebug>

#define INSTANCE DBManager::getInstance()

AppDataModel::AppDataModel(QObject *parent)
    : QAbstractListModel(parent)
{
    // TEST DATA
    // const static char *APP_EXAM[] = {
    //     "WPS",
    //     "Wechat",
    //     "QQ",
    //     "Chrome",
    //     "Setting",
    //     "Photo",
    //     "Manage"
    // };
    // for (int i = 0; i < 5; ++i) {
    //     m_appData.push_back({APP_EXAM[rand() % 6], "qrc:/img/app.png"});
    // }
    INSTANCE.openDatabase("/home/mike/aqs-desktop-component/appInfo.db");
    QSqlQuery query = INSTANCE.execQuery("SELECT * FROM Icon;");
    if (query.isActive()) {
        while (query.next()) {
            m_appData.push_back({query.value(0).toString(), "file:/" + query.value(1).toString()});
        }
    } else {
        m_appData.push_back({"SELECT FAILED", ""});
    }
}

AppDataModel::~AppDataModel()
{
    DBManager::getInstance().closeDatabase();
}

int AppDataModel::rowCount(const QModelIndex &) const
{
    return m_appData.count();
}

QVariant AppDataModel::data(const QModelIndex &index, int role) const
{
    if (index.row() < rowCount()) {
        switch (role) {
        case AppNameRole:
            return m_appData.at(index.row()).appName;
        case AppIconRole:
            return m_appData.at(index.row()).appIcon;
        default:
            return QVariant();
        }
    }
    return QVariant();
}

QHash<int, QByteArray> AppDataModel::roleNames() const
{
    static const QHash<int, QByteArray> roles {
                                              { AppNameRole, "appName" },
                                              { AppIconRole, "appIcon" },
                                              };
    return roles;
}

QVariantMap AppDataModel::get(int row) const
{
    const Entity e = m_appData.value(row);
    return {
        {"appName", e.appName},
        {"appIcon", e.appIcon}
    };
}

void AppDataModel::append(const QString &appName, const QString &appIcon)
{
    int row = 0;
    while (row < m_appData.count() && appName > m_appData.at(row).appName)
        ++row;
    beginInsertRows(QModelIndex(), row, row);
    m_appData.insert(row, {appName, appIcon});
    endInsertRows();
}

// void AppDataModel::set(int row, const QString &fullName, const QString &address, const QString &city, const QString &number)
// {
//     return;
// }

void AppDataModel::remove(int row)
{
    // USE: appModel.remove(index)
    if (row < 0 || row >= m_appData.count()) {
        return;
    }
    beginRemoveRows(QModelIndex(), row, row);
    m_appData.removeAt(row);
    endRemoveRows();
}

int AppDataModel::type() const
{
    return m_modelType;
}

void AppDataModel::setType(const int type)
{
    m_modelType = type;
    // if (m_modelType == SPECIAL)
    // m_appData.clear();
    emit typeChanged(m_modelType);
}
